using UnityEngine;
using System.Collections;

public class BulletBehaviour : MonoBehaviour
{
	//Velocidade do tiro(pixel por segundo)
	[SerializeField]
	private float speed	= 200;
	//Explosao que toca quando tiro colide
	[SerializeField]
	private ExplosionBehaviour explosion;
	
	//Tentar empurrar quando acertar o tiro
	[SerializeField]
	private bool pushOnHit = false;
	
	//Personagem que lancou esse projétil
	[HideInInspector]
	public CharacterBehaviour myCharacter;
	//Dano que causará quando colidir
	[HideInInspector]
	public int damage;
	
	//Renderer para checar se saiu da tela
	private Renderer myRenderer;
	
	//Detectar se colidiu
	private DetectorCollider detector;
	
	void Awake()
	{
		myRenderer = GetComponentInChildren<Renderer>();
		detector = GetComponent<DetectorCollider>();
	}
	
	void Update()
	{
		transform.Translate(Vector3.right * speed * Time.deltaTime, Space.Self);
		
		if(!detector.IsFree)
		{
			foreach(GameObject g in detector.GetObjects)
			{
				if(g.GetComponent<CharacterBehaviour>())
				{
					bool diedAny = false;
					
					if(pushOnHit)
					{
						diedAny = g.GetComponent<CharacterBehaviour>().Hit(damage,
								  (transform.localEulerAngles.z > 0), false);
					}
					else
					{
						diedAny = g.GetComponent<CharacterBehaviour>().Hit(damage, false);
					}
					
					if(myCharacter && diedAny)
					{
						myCharacter.diedAnEnemy ++;
					}
					
					break;
				}
			}
			
			Instantiate(explosion.gameObject, transform.position, Quaternion.identity);
			Destroy(gameObject);
		}
		
		if(!myRenderer.isVisible)
		{
			Destroy(gameObject);
		}
	}
}
